package thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: a
 * Date: 2022-10-07
 * Time: 21:26
 */

//模拟实现线程池
class MyThreadPool{
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }

    public MyThreadPool(int nThreads){
        for(int i = 0; i < nThreads; i++){
            Thread thread = new Thread(() -> {
                while(!Thread.currentThread().isInterrupted()){
                    try {
                        Runnable runnable = queue.take();
                        runnable.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;
                    }
                }
            });
            thread.start();
        }
    }
}

public class Demo14 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool = new MyThreadPool(10);
        for(int i = 0; i < 100; i++){
            myThreadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("main");
                }
            });
        }
    }
}
